<?php

defined('SYSPATH') or die('No direct access allowed.');

class Model_Main extends Model {

    public function update_regions($id, $name) {
        $region_model = ORM::factory('region')->where("reg_id", "=", $id)->find();
        $region_model->reg_id = $id;
        $region_model->name = $name;
        if ($region_model->loaded()) {
            $region_model->update();
        } else {
            $region_model->save();
        }
    }

    public function update_projects($project_id, $project_domain, $region_id) {
        $projects_model = ORM::factory('project')->where("project_id", "=", $project_id)->find();
        $projects_model->project_id = $project_id;
        $projects_model->domain = $project_domain;
        $projects_model->region_id = $region_id;
        if (!$projects_model->loaded()) {
            $projects_model->create();
            $projects_model->clear();
        } else {
            $projects_model->update();
        }
    }

    public function update_queries($query_id, $project_id, $query_title, $query_target) {
        $model_queries = ORM::factory('query')->where("query_id", "=", $query_id)->find();
        $model_queries->query_id = $query_id;
        $model_queries->project_id = $project_id;
        $model_queries->title = $query_title;
        $model_queries->target = $query_target;
        if (!$model_queries->loaded()) {
            $model_queries->create();
            $model_queries->clear();
        } else {
            $model_queries->update();
        }
    }

    public function update_positions($query_id, $date, $yandex, $google) {
        $model_position = ORM::factory('position')->where("query_id", "=", $query_id)
                        ->and_where("date", "=", strtotime($date))->find();
        $model_position->query_id = $query_id;
        $model_position->yandex = $yandex;
        $model_position->google = $google;
        $model_position->date = strtotime($date);
        if (!$model_position->loaded()) {
            $model_position->save();
        }
    }

    public function get_positions($query_id, $interval) {
        $model_position = ORM::factory('position')->where("query_id", "=", $query_id)
                        ->and_where("date", ">", $interval)
                        ->and_where("date", "<", strtotime(date("Y-m-d")))->find_all();
        return $model_position;
    }

}